//
//  HomeViewController.m
//  meitu
//
//  Created by Liccon Chang on 12-6-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "UIColor+HTML.h"
#import <QuartzCore/QuartzCore.h>
#import "tyconsts.h"
#import "DialogUtil.h"
#import "AppDelegate.h"

static NSString* const KNotificationShowNewFlag=@"KNotificationShowNewFlag";//在主页下显示new

@implementation HomeViewController

@synthesize adView=adView_;
@synthesize orderBy=orderBy_;
@synthesize subItem=subItem_;
@synthesize isRecommend=isRecommend_;
@synthesize isFirstTab=isFirstTab_;

- (void)loadView {
    [super loadView];
    mainTable_.separatorStyle=UITableViewCellSeparatorStyleNone;
    orderBy_=2;
    self.view.backgroundColor=[UIColor whiteColor];
    if ([[self.navigationController viewControllers] count]<=1)
    {
        [self setNavigationLeftButtonWithImage:[UIImage imageNamed:@"refresh.png"] hightlightedImage:nil target:self action:@selector(onRefresh)];
    }
    [self setNavigationRightButtonWithImage:[UIImage imageNamed:@"type.png"] hightlightedImage:nil target:self action:@selector(onChangeorderBy)];
    UIButton* btnView=(UIButton*)[self navigationItem].leftBarButtonItem.customView;
    UIActivityIndicatorView* refreshIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    refreshIndicator.tag=98766;
	refreshIndicator.frame = CGRectMake(5, 5, 33, 29);
    refreshIndicator.hidden=TRUE;
    [btnView addSubview:refreshIndicator];
    [refreshIndicator release];
    self.textLastTime=[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    if (isFirstTab_)
    {
        [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(showNewFlag) userInfo:nil repeats:NO];
    }
}

//- (void)onRefresh
//{
//    if ([self.textLastTime length]>0)
//    {
//        NSTimeInterval nowTime=[[NSDate date] timeIntervalSince1970];
//        NSTimeInterval lastTime=[self.textLastTime doubleValue];
//        if (nowTime-lastTime>30)
//        {
//            [self scrollTableToHead:FALSE];
//            mainTable_.contentOffset=CGPointMake(0, -48);
//            [self changeBackgroundViewFrame];
//            [self startLoading];
//        }
//    }
//}

- (void)tabClickAgain
{
    if (mainTable_.contentOffset.y > 0)
    {
        [self scrollTableToHead:TRUE];
    }
    else
    {
        [self onRefresh];
    }
}

- (void)showNewFlag
{
    NSTimeInterval nowTime=[[NSDate date] timeIntervalSince1970];
    NSTimeInterval lastTime=[self.textLastTime doubleValue];
    if (nowTime-lastTime>30 && [feeds_ count]>0)
    {
        NSDictionary* paremDict=[NSDictionary dictionaryWithObject:@"1" forKey:@"new"];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationShowNewFlag object:paremDict];
    }
    [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(showNewFlag) userInfo:nil repeats:NO];
}

- (void)setNavigationLeftButtonWithIndicator
{    
    UIButton* btnView=(UIButton*)[self navigationItem].leftBarButtonItem.customView;
    //btnView.enabled=FALSE;
    [btnView setImage:[UIImage imageNamed:@"nav_bg.png"] forState:UIControlStateNormal];
    UIActivityIndicatorView* refreshIndicator = (UIActivityIndicatorView*)[btnView viewWithTag:98766];
    refreshIndicator.hidden=FALSE;
    [refreshIndicator startAnimating];
    [btnView bringSubviewToFront:refreshIndicator];
}

- (void)endRefreshAnimated
{
    UIButton* btnView=(UIButton*)[self navigationItem].leftBarButtonItem.customView;
    //btnView.enabled=TRUE;
    [btnView setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
    UIActivityIndicatorView* refreshIndicator = (UIActivityIndicatorView*)[btnView viewWithTag:98766];
    [refreshIndicator stopAnimating];
    refreshIndicator.hidden=TRUE;
    [self navigationItem].leftBarButtonItem.enabled=TRUE;
}

- (void)onChangeorderBy
{
    UIActionSheet*actionSheet = [[UIActionSheet alloc] 
                                 initWithTitle:@""
                                 delegate:self  
                                 cancelButtonTitle:nil
                                 destructiveButtonTitle:nil
                                 otherButtonTitles:@"最新发表",@"最新回复",@"取消",nil];
    actionSheet.cancelButtonIndex = 2;
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    
    [actionSheet showInView:[self.view window]];
    
    [actionSheet release];
}

- (void)refresh
{
    [super refresh];
    if ([[self.navigationController viewControllers] count]<=1)
    {
        [self setNavigationLeftButtonWithIndicator];
    }
}

- (void)endRefresh 
{
    if ([[self.navigationController viewControllers] count]<=1)
    {
        [self performSelector:@selector(endRefreshAnimated) withObject:nil afterDelay:1.0];
    }
    if (isFirstTab_)
    {
        NSDictionary* paremDict=[NSDictionary dictionaryWithObject:@"0" forKey:@"new"];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationShowNewFlag object:paremDict];
    }
}

- (void)showGetMoreWaittingView
{
    if (getMoreWaittingView_==nil)
    {
        getMoreWaittingView_ = [UIButton buttonWithType:UIButtonTypeCustom];
        [getMoreWaittingView_ setBackgroundColor:[UIColor colorWithHTMLName:@"#D3E0E8"]];
        CGRect rect=CGRectMake(0, mainTable_.frame.origin.y+mainTable_.frame.size.height-40, 320, 40);
        getMoreWaittingView_.frame = rect;
        //[getMoreWaittingView_ addTarget:self action:@selector(showMore) forControlEvents:UIControlEventTouchUpInside];
        
        loadingSpinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        loadingSpinner_.frame = CGRectMake(15,10,20,20);
        loadingSpinner_.hidesWhenStopped = YES;
        [getMoreWaittingView_ addSubview:loadingSpinner_];
        [loadingSpinner_ release];
    
        UILabel* moreLabel=[[UILabel alloc] initWithFrame:CGRectMake(40, 0, 250, 40)];
        moreLabel.textColor=[UIColor whiteColor];
        moreLabel.text=@"加载中";
        moreLabel.backgroundColor=[UIColor clearColor];
        [getMoreWaittingView_ addSubview:moreLabel];
        [moreLabel release];
        [self.view addSubview:getMoreWaittingView_];//mainTable_.tableFooterView = getMoreWaittingView_;//
    }
    [loadingSpinner_ startAnimating];
    mainTable_.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
    getMoreWaittingView_.hidden=FALSE;
    [self showMore];
}

- (void)hideGetMoreWaittingView
{
    UIEdgeInsets edgeInsets=mainTable_.contentInset;
    edgeInsets.bottom=0;
    mainTable_.contentInset = edgeInsets;
    getMoreWaittingView_.hidden=TRUE;
    [loadingSpinner_ stopAnimating];
}

- (void)showWaitingView
{
    [DialogUtil showWaitingViewWithMessage:@""];
//    CGRect frame=CGRectMake(0, 0, 80, 80);
//    firstLoadingView_=[[UIView alloc] initWithFrame:frame];
//    firstLoadingView_.layer.cornerRadius=5.0;
//    firstLoadingView_.center=self.view.center;
//    firstLoadingView_.backgroundColor=[UIColor colorWithHTMLName:@"#7F7F7F"];
//    UIActivityIndicatorView* loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//    loading.frame = CGRectMake(25,10,30,30);
//    loading.hidesWhenStopped = YES;
//    [firstLoadingView_ addSubview:loading];
//    [loading release];
//    
//    UILabel* moreLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 50, 80, 30)];
//    moreLabel.textColor=[UIColor whiteColor];
//    moreLabel.textAlignment=UITextAlignmentCenter;
//    moreLabel.text=@"加载中";
//    moreLabel.backgroundColor=[UIColor clearColor];
//    [firstLoadingView_ addSubview:moreLabel];
//    [moreLabel release];
//    [loading startAnimating];
//    [self.view addSubview:firstLoadingView_];
}

- (void)hideWaitingView
{
    [DialogUtil hideWaitingView];
}

#pragma mark -
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	switch (buttonIndex)
    {
        case 0://最新发表
            {
                if (orderBy_==2)
                {
                    orderBy_=1;
                    [self onRefresh];
                }
            }
			break;
		case 1://最新回复
            {
                if (orderBy_==1)
                {
                    orderBy_=2;
                    [self onRefresh];
                }
            }
            break;
    }
}

#pragma mark -
#pragma mark ListNetworkViewController
- (BOOL)requestListData:(BOOL)refresh
{
    if ([super requestListData:refresh]) 
    {
        int nextId = 0;
        NSString* nextTime = @"";
        if (!refresh && listFeeds_)//取更多
        {
            NoteInfo* item = (NoteInfo*)[listFeeds_ lastObject];
            nextId = item.idd;
            nextTime = item.replyTime;
        }
        if (isRecommend_)
        {
            listRequest_=[Request requestGradeNoteInfoListWithCategoryId:categoryId_ nextTime:nextTime orderBy:orderBy_ delegate:self];
        }
        else
        {
            listRequest_=[Request requestNoteInfoListWithCategoryId:categoryId_ nextId:nextId nextTime:nextTime orderBy:orderBy_ subItem:subItem_ delegate:self];
        }
        return TRUE;
    }
    return FALSE;
}

#pragma mark -
#pragma mark ASIHTTPRequest
- (void)requestFinished:(ASIHTTPRequest *)request 
{
    [super requestFinished:request];
    if ([listFeeds_ count]>0)
        mainTable_.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    if (isRefresh_)
    {
        [self endRefresh];
        if ([listFeeds_ count]>0)
        {
            if (freshLabel_==nil)
            {
                freshLabel_=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
                freshLabel_.text=@"  已获取新数据";
                freshLabel_.textColor=[UIColor colorWithHTMLName:@"#300000"];
                freshLabel_.backgroundColor=[UIColor colorWithHTMLName:@"#f4e320"];
                freshLabel_.hidden=TRUE;
            }
            freshLabel_.hidden=FALSE;
            [self.view addSubview:freshLabel_];
            [freshLabel_ release];
            [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(hideFreshLabel) userInfo:nil repeats:NO];
        }
    }
}

- (void)hideFreshLabel
{
    [freshLabel_ removeFromSuperview];
    freshLabel_=nil;
}

- (void)requestFailed:(ASIHTTPRequest *)request 
{
	[super requestFailed:request];
    if (isRefresh_)
    {
        [self endRefresh];
    }
}

#pragma mark -
#pragma mark 实现广告功能
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* showAd = [defaults objectForKey:@"showAd"];
    if (showAd ==nil || [showAd isEqualToString:@"1"])
    {
        adView_ = [[AdMoGoView alloc] initWithAppKey:[self getAppKey]
                                              adType:AdViewTypeNormalBanner
                                         expressMode:NO
                                  adMoGoViewDelegate:self];
        adView_.adWebBrowswerDelegate = self;
        adView_.frame = CGRectZero;
        [self.view addSubview:adView_];
    }
}

- (NSString*)getAppKey
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* appKey = [defaults objectForKey:@"appKey"];
    if (appKey ==nil || [appKey length]<=0)
    {
        return AD_APPKEY;//@"407e4f68caf54c61a7da44216fe1ea17";
    }
    return appKey;
}

#pragma mark -
#pragma mark AdMoGoDelegate delegate 
/*
 返回广告rootViewController
 */
- (UIViewController *)viewControllerForPresentingModalView{
    return self.tabBarController;//返回的对象为adView_的父视图控制器
}

/**
 * 广告开始请求回调
 */
- (void)adMoGoDidStartAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告开始请求回调");
}
/**
 * 广告接收成功回调
 */
- (void)adMoGoDidReceiveAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告接收成功回调");
    [self showAdjustAdSize];
    //[NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(hideAdjustAdSize) userInfo:nil repeats:NO];
}
/**
 * 广告接收失败回调
 */
- (void)adMoGoDidFailToReceiveAd:(AdMoGoView *)adMoGoView didFailWithError:(NSError *)error{
    NSLog(@"广告接收失败回调");
    [self hideAdjustAdSize];
}
/**
 * 点击广告回调
 */
- (void)adMoGoClickAd:(AdMoGoView *)adMoGoView{
    NSLog(@"点击广告回调");
}
/**
 *You can get notified when the user delete the ad 
 广告关闭回调
 */
- (void)adMoGoDeleteAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告关闭回调");
}

#pragma mark -
#pragma mark AdMoGoWebBrowserControllerUserDelegate delegate 

/*
 浏览器将要展示
 */
- (void)webBrowserWillAppear{
    NSLog(@"浏览器将要展示");
}

/*
 浏览器已经展示
 */
- (void)webBrowserDidAppear{
    NSLog(@"浏览器已经展示");
}

/*
 浏览器将要关闭
 */
- (void)webBrowserWillClosed{
    NSLog(@"浏览器将要关闭");
}

/*
 浏览器已经关闭
 */
- (void)webBrowserDidClosed{
    NSLog(@"浏览器已经关闭");
}

/*
 浏览器分享
 */
- (void)webBrowserShare:(NSString *)url
{
    NSLog(@"浏览器分享:%@",url);
}

- (void)showAdjustAdSize {
    if ([feeds_ count]>0)
    {
    //	[UIView beginAnimations:@"AdResize" context:nil];
    //	[UIView setAnimationDuration:0.7];
        CGSize adSize = adView_.frame.size;
        CGRect newFrame = adView_.frame;
        newFrame.size.height = adSize.height;
        newFrame.size.width = adSize.width;
        newFrame.origin.x = 0;
        newFrame.origin.y = self.view.frame.size.height-adSize.height;
        adView_.frame = newFrame;
    //    newFrame=mainTable_.frame;
    //    //newFrame.origin.y+=adSize.height;
    //    newFrame.size.height-=adSize.height;
    //    mainTable_.frame=newFrame;
    //	[UIView commitAnimations];
    }
    else
    {
         adView_.frame = CGRectZero;
    }
}

- (void)hideAdjustAdSize {
    if (!CGRectIsEmpty(adView_.frame)) {
        [UIView beginAnimations:@"AdResize" context:nil];
        [UIView setAnimationDuration:0.7];
        CGSize adSize = adView_.frame.size;
        CGRect newFrame = adView_.frame;
        newFrame.origin.y+=adSize.height;
        newFrame.size.height=0;
        adView_.frame = newFrame;
        newFrame=mainTable_.frame;
        newFrame.origin.y=0;
        newFrame.size.height+=adSize.height;
        mainTable_.frame=newFrame;
        [UIView commitAnimations];
    }
}

- (void)dealloc {
    adView_.delegate = nil;
    adView_.adWebBrowswerDelegate = nil;
    [adView_ release];
    [subItem_ release];
    [super dealloc];
}

@end
